package com.hamizhong.iflowers.web.action;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.Cookie;

import com.hamizhong.iflowers.utils.MyColumnIndicator;
import com.hamizhong.iflowers.utils.MyConstants;
import com.hamizhong.iflowers.web.base.MyBaseAction;

public class AjaxChangGoodsCntInCartAction extends MyBaseAction {

	@Override
	protected String doRequest() {
		logger.info("----------------- Hello AjaxChangGoodsCntInCartAction -----------------");
		String goodsId = getRQ().getParameter("goodsId");
		String flag = getRQ().getParameter("flag");
		PrintWriter pw = null;
		try {
			pw = getPW();
		} catch (Exception e) {
			e.printStackTrace();
			return "failed";
		}
		
		String cartGoodsArrStr = "";
		String newCartGoodsArrStr = "";
		
		String[] arr0;
		String[] arr1;
		String[] arr2;
		String[] arr3;
		
		boolean isExist = false;
		
		try {
			Cookie[] cookie = getRQ().getCookies();
			if(cookie != null) {
				for(int i=0;i<cookie.length;i++) {
					String res = cookie[i].getName();
					if(res.equals("iFlowers_Shopping_Cart")) {
						cartGoodsArrStr = cookie[i].getValue();
						break;
					}
				}
			}
			if(cartGoodsArrStr != "") {
				arr1 = cartGoodsArrStr.split("_");
				arr2 = new String[arr1.length];
				arr3 = new String[arr1.length];

				for(int i=0;i<arr1.length;i++) {
					arr0 = new String[2];
					arr0 = arr1[i].split("-");
					arr2[i] = arr0[0];
					arr3[i] = arr0[1];
				}
				for(int i=0;i<arr2.length;i++) {
					if(arr2[i].equals(String.valueOf(goodsId))) {
						isExist = true;
						if(flag.equals("+")) {
							int oldCnt = Integer.valueOf(arr3[i]);
							arr3[i] = String.valueOf(++oldCnt);
						}else {
							int oldCnt = Integer.valueOf(arr3[i]);
							arr3[i] = String.valueOf(--oldCnt);
						}
						break;
					}
				}
				if(!isExist) {
					pw.write("NotExist");
					return null;
				}
				for(int i=0;i<arr2.length;i++) {
					newCartGoodsArrStr += arr2[i]+"-"+arr3[i]+"_";
				}
				pw.write(newCartGoodsArrStr);
				return null;
			}else {
				pw.write("NotExist");
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			pw.write("failed");
			return null;
		}
	}
}
